package com.example.research.utils;

import com.example.research.entity.User;
import com.example.research.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 权限验证工具类
 */
@Component
public class PermissionUtils {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 验证用户是否为管理员
     */
    public boolean isAdmin(String token) {
        try {
            Long userId = jwtUtils.getUserIdFromToken(token);
            User user = userService.getUserById(userId);
            return "ADMIN".equals(user.getRole());
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 验证用户是否为教师
     */
    public boolean isTeacher(String token) {
        try {
            Long userId = jwtUtils.getUserIdFromToken(token);
            User user = userService.getUserById(userId);
            return "TEACHER".equals(user.getRole());
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 验证用户是否为学生
     */
    public boolean isStudent(String token) {
        try {
            Long userId = jwtUtils.getUserIdFromToken(token);
            User user = userService.getUserById(userId);
            return "STUDENT".equals(user.getRole());
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 验证教师是否负责该学生
     */
    public boolean isTeacherOfStudent(String token, Long studentId) {
        try {
            Long teacherId = jwtUtils.getUserIdFromToken(token);
            User student = userService.getUserById(studentId);
            String studentTeacherId = student.getTeacherId();
            return studentTeacherId != null && teacherId.toString().equals(studentTeacherId);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 验证是否可以修改/删除（审核通过后不可修改）
     */
    public boolean canModifyAchievement(Integer auditStatus) {
        return auditStatus == null || auditStatus != 1; // 1表示审核通过
    }

    /**
     * 获取当前用户ID
     */
    public Long getCurrentUserId(String token) {
        try {
            return jwtUtils.getUserIdFromToken(token);
        } catch (Exception e) {
            throw new RuntimeException("无法获取当前用户信息");
        }
    }

    /**
     * 获取当前用户信息
     */
    public User getCurrentUser(String token) {
        try {
            Long userId = jwtUtils.getUserIdFromToken(token);
            return userService.getUserById(userId);
        } catch (Exception e) {
            throw new RuntimeException("无法获取当前用户信息");
        }
    }
}
